package com.hz.cheetah.sample.client;

import com.hz.cheetah.sample.api.HelloService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@ContextConfiguration(locations = {"classpath*:/spring.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class HelloClient4 {

    @Autowired()
    @Qualifier("HelloService")
    HelloService helloService;

    AtomicInteger count = new AtomicInteger();

    private static final Logger LOGGER = LoggerFactory.getLogger(HelloClient4.class);

    @Test
    public void testList() throws Exception {

        int threadNum = 10;
        int loopCount = 100000;


        ExecutorService executor = Executors.newFixedThreadPool(threadNum);
        final CountDownLatch latch = new CountDownLatch(loopCount);

        try {
            long start = System.currentTimeMillis();

            for (int i = 0; i < loopCount; i++) {
                final int finalI = i;
                executor.submit(new Runnable() {
                    @Override
                    public void run() {
                        String result = helloService.hello("World");
                        //LOGGER.info(finalI +":"+result);
                        if(result == null){
                            count.incrementAndGet();
                        }
                        System.out.println(result);
                        latch.countDown();
                    }
                });
            }
            latch.await();
            CountDownLatch latch2 = new CountDownLatch(1);
            long time = System.currentTimeMillis() - start;
            System.out.println(count.get());
            System.out.println("thread: " + threadNum);
            System.out.println("loop: " + loopCount);
            System.out.println("time: " + time + "ms");
            System.out.println("tps: " + (double) loopCount / ((double) time / 1000));
            latch2.await(10000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
        }


    }
}
